package com.czk.protocol.http;

import com.czk.framework.Invocation;
import com.czk.provider.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/14 16:41
 */
public class HttpServerHandler {
    public void handler(HttpServletRequest request, HttpServletResponse response){
        // 拿到输入流
        try {

            ServletInputStream inputStream = request.getInputStream();
            // 包装
            ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);
            // 转换
            Invocation invocation=(Invocation)objectInputStream.readObject();
            // 拿到class
            Class clazz = LocalRegister.get(invocation.getInterfaceName());
            // 拿到方法的反射
            Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            // 执行方法
            String invoke = (String) method.invoke(clazz.newInstance(), invocation.getParams());
            System.out.println("http-----------"+invoke);
            // 返回数据
            IOUtils.write(invoke,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
